﻿using System;
using GammaJul.ReSharper.GammaXaml.Psi.Xaml;
using JetBrains.Annotations;
using JetBrains.ReSharper.Feature.Services.Bulbs;
using JetBrains.ReSharper.Feature.Services.Xaml.Bulbs;
using JetBrains.ReSharper.Intentions.Extensibility;
using JetBrains.ReSharper.Intentions.Extensibility.Menu;
using JetBrains.Util;

namespace GammaJul.ReSharper.GammaXaml.ContextActions.Xaml {

	/// <summary>
	/// A quick fix that presents a group of <see cref="RemoveGridDefinitionItem"/>, used to remove rows or columns from a grid.
	/// </summary>
	[ContextAction(Name = "Remove grid definition", Group = "XAML", Description = "Remove a RowDefinition or ColumnDefinition from a Grid.")]
	public class RemoveGridDefinitionAction : IContextAction {
		private readonly XamlContextActionDataProvider _provider;
		private GridDefinitionType? _definitionType;

		public void CreateBulbItems(BulbMenu menu) {
			if (_definitionType == null)
				return;

			BulbGroup group = menu.GetOrCreateGroup(AnchorsForBulbMenuGroups.ContextActionsAnchor);
			BulbMenuItem definitionMenu = group.GetOrCreateSubmenu(GridContextActionBulbMenus.DefinitionManagementDescription);
			definitionMenu.Submenu.ArrangeContextAction(new RemoveGridDefinitionItem(_provider, _definitionType.Value));
		}

		private bool HasDefinitionAtCaret(GridDefinitionType definitionType) {
			if (GridDefinitionItemBase.HasDefinitionAtCaret(_provider, definitionType)) {
				_definitionType = definitionType;
				return true;
			}
			return false;
		}

		public bool IsAvailable(IUserDataHolder cache) {
			return HasDefinitionAtCaret(GridDefinitionType.Row)
				|| HasDefinitionAtCaret(GridDefinitionType.Column);
		}

		public RemoveGridDefinitionAction([NotNull] XamlContextActionDataProvider provider) {
			if (provider == null)
				throw new ArgumentNullException("provider");
			_provider = provider;
		}
	}

}